package com.yimi.policyservice.repository;

import com.yimi.policyservice.entity.base.policy.PolicySocialItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface PolicySocialItemRepository extends JpaRepository<PolicySocialItem,String> {
    @Modifying
    @Transactional
    @Query(value = "delete  from t_policy_social_item where product_id in ?1",nativeQuery = true)
    void deleteByProductIdIn(List<String> ids);


    List<PolicySocialItem> findByProductId(String id);

    @Query(value = "select item_type_code from t_policy_social_item where product_id =?1",nativeQuery = true)
    List<String> findItemTypeCodeByProductId(String productId);

    PolicySocialItem findFirstByProductIdAndItemTypeCode(String productId, String code);

    @Modifying
    @Transactional
    @Query(value = "update  t_policy_social_item item set item.group_uuid = ?3 where item.product_id = ?1 and (item.group_uuid  in " +
            "(select a.group_uuid from (select  group_uuid from  t_policy_social_item where product_id=?1 and item_type_code in ?2 " +
            ") a)  OR item.item_type_code in ?2 ) ",nativeQuery = true)
    int  updateGroupIdByCode(String productId, List<String> itemGroupCodes, String groupId);

    @Query(value = "select item_type_code from t_policy_social_item where product_id =?1 and id <> ?2 and group_uuid = ?3",nativeQuery = true)
    List<String> findOtherGroupCodes(String productId, String id, String groupUuid);
    @Modifying
    @Transactional
    @Query(value = "update t_policy_social_item set group_uuid=null where product_id =?1 and group_uuid = ?2" ,nativeQuery = true)
    int clearnGroupIdByProductId(String productId,String groupyId);
    @Modifying
    @Transactional
    @Query(value = "delete from  t_policy_social_item  where product_id =?1 and item_type_code = ?2" ,nativeQuery = true)
    int deletecode(String productId, String code);

    @Query(value = "select item_type_code " +
            "from t_policy_social_item " +
            "where product_id = ?1 " +
            "and ( group_uuid  in (select group_uuid from t_policy_social_item where product_id=?1 and item_type_code=?2) " +
            "  or group_uuid is null )  ",nativeQuery = true)
    List<String> findGroupdCodeByPid(String productId,String code);
}
